package com.hjj.springboot.controller.admin;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hjj.springboot.config.LogType;
import com.hjj.springboot.config.SystemLogs;
import com.hjj.springboot.entity.*;
import com.hjj.springboot.service.ICommentService;
import com.hjj.springboot.service.IProductService;
import com.hjj.springboot.service.IWxUserInfoService;
import com.hjj.springboot.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/comment")
public class AdminCommentController {

    @Autowired
    private ICommentService commentService;

    @Autowired
    private IWxUserInfoService wxUserInfoService;

    @Autowired
    private IProductService productService;

    @RequestMapping("/list")
    public R list(@RequestBody PageBean pageBean){
        String query=pageBean.getQuery().trim();
        Page<Comment> page=new Page<>(pageBean.getPageNum(),pageBean.getPageSize());
        Page<Comment> pageResult = commentService.page(page,new QueryWrapper<Comment>().like(StringUtil.isNotEmpty(query),"scores",query));
        for (Comment comment:pageResult.getRecords()){
            comment.setWxUserInfo(wxUserInfoService.getOne(new QueryWrapper<WxUserInfo>().eq("openid",comment.getUId())));
            comment.setProduct(productService.getOne(new QueryWrapper<Product>().eq("id",comment.getGId())));
        }
        Map<String,Object> map=new HashMap<>();
        map.put("total",pageResult.getTotal());
        map.put("commentList",pageResult.getRecords());
        return R.ok(map);
    }

    @SystemLogs(operation = "用户评价",type = LogType.DELETE)
    @GetMapping("/delete/{id}")
    public R delete(@PathVariable(value = "id")Integer id) {
        commentService.removeById(id);
        return R.ok();
    }

    //    批量删除
    @SystemLogs(operation = "用户评价",type = LogType.BATCH_DELETE)
    @PostMapping("/deleteBatch")
    public R deleteBatch(@RequestBody List<Integer> ids) {
        commentService.removeByIds(ids);
        return R.ok();
    }

    @GetMapping("/export")
    public void export(@RequestParam(required = false) String query, HttpServletResponse response)   throws Exception {
        String queryStr=query.trim();
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("商品评价信息", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        List<Comment> commentList = commentService.list(new QueryWrapper<Comment>().like(StringUtil.isNotEmpty(queryStr),"scores",query));
        EasyExcel.write(response.getOutputStream(),Comment.class)
                .sheet("商品评价信息")
                .doWrite(commentList);
    }

    @RequestMapping("/radarCharts")
    public R radarCharts(){
        // 获取评论列表
        List<Comment> commentList = commentService.list();

        // 使用Stream API按gId分组，并计算每个组的平均评分、最高评分和最低评分
        Map<Integer, DoubleSummaryStatistics> groupedScores = commentList.stream()
                .collect(Collectors.groupingBy(Comment::getGId,
                        Collectors.summarizingDouble(Comment::getScores))); // 确保Comment类有getScores方法

        // 初始化四个列表
        List<Map<String, Object>> productDataList = new ArrayList<>();
        List<Double> averageScoreList = new ArrayList<>();
        List<Double> maxScoreList = new ArrayList<>();
        List<Double> minScoreList = new ArrayList<>();

        // 遍历分组结果，提取所需的数据
        groupedScores.forEach((gId, stats) -> {
            // 获取对应gId的产品信息
            Product product = productService.getOne(new QueryWrapper<Product>().eq("id", gId));
            Map<String, Object> productData = new HashMap<>();
            if (product != null) {
                productData.put("name", product.getName());
                productData.put("value", 5); // 最高评分设置为5分
            }
            productDataList.add(productData);

            // 添加评分统计数据到对应的列表
            averageScoreList.add(stats.getAverage());
            maxScoreList.add(stats.getMax());
            minScoreList.add(stats.getMin());
        });

        // 创建一个用于存放所有数据的映射
        Map<String, Object> map = new HashMap<>();
        map.put("productData", productDataList);
        map.put("averageScore", averageScoreList);
        map.put("maxScore", maxScoreList);
        map.put("minScore", minScoreList);

        // 返回包含雷达图数据的响应
        return R.ok(map);
    }

}
